package com.yuebu.bluetoothbandsdk;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yuebu.bluetoothbandsdk.adapter.SearchListAdapter;
import com.yuebu.bluetoothbandsdk.utils.PermissionUtils;
import com.yuebu.bluetoothbandsdk.utils.SPUtils;
import com.yuebu.bluetoothbandsdk.widget.CustomProgressDialog;
import com.yuebu.yuebubtlib.BLEScanner;
import com.yuebu.yuebubtlib.BandCommAgent;
import com.yuebu.yuebubtlib.Constants;
import com.yuebu.yuebubtlib.bean.DeviceTimeBean;
import com.yuebu.yuebubtlib.exception.BLEException;
import com.yuebu.yuebubtlib.listener.BluetoothSignalListener;
import com.yuebu.yuebubtlib.util.BLEByteUtil;
import com.yuebu.yuebubtlib.util.BLELogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.BreakIterator;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Button btnSearch;
    private static final int REQUEST_LOCATION_CODE = 100;      //请求位置权限
    private RecyclerView recyclerView;
    private SearchListAdapter listAdapter;
    private Long onClickTime = 0l;
    private Long mLastClickTime = 0l;

    private  int index=0;

    private ArrayList<String> deviceAddressList = new ArrayList<>();
    private SPUtils spUtils;
    private BandCommAgent bandCommAgent;
    private String macAddress;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    CustomProgressDialog.show(MainActivity.this);
                    bandCommAgent.connect(macAddress);
                    break;
            }
        }
    };
    private boolean spinner_doingfun_sel;
    private EditText tv_device_name;
    private EditText ed_ver;
    private EditText etFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (checkSDK()) {
            PermissionUtils.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION,
                            android.Manifest.permission.READ_EXTERNAL_STORAGE,
                            android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_LOCATION_CODE,
                    "5.0之后使用蓝牙需要位置权限",
                    new PermissionUtils.OnPermissionResult() {
                        @Override
                        public void granted(int requestCode) {

                        }

                        @Override
                        public void denied(int requestCode) {

                        }
                    });
        }
        bandCommAgent = BandCommAgent.getInstance(this);
//        EventBus.getDefault().register(this);
        /**
         * 判断是否开启蓝牙
         */
        if (!bandCommAgent.isOpenBluetooth()) {
            bandCommAgent.openBluetooth();
        }
        spUtils = SPUtils.getInstance(this);
        recyclerView = findViewById(R.id.recyclerview);
        btnSearch = findViewById(R.id.btn_search);
        initRecyclerView();
        initListener();
        //initData();

    }

    //检测通知监听服务是否被授权
    public boolean isNotificationListenerEnabled(Context context) {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(context.getPackageName())) {
            return true;
        }
        return false;
    }

    //打开通知监听设置页面
//    public void openNotificationListenSettings() {
//        try {
//            Intent intent;
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
//                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
//            } else {
//                intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
//            }
//            startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    //把应用的NotificationListenerService实现类disable再enable，即可触发系统rebind操作
//    private void toggleNotificationListenerService() {
//        PackageManager pm = getPackageManager();
//        pm.setComponentEnabledSetting(
//                new ComponentName(getApplication(), MyNotificationListenerService.class),
//                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
//
//        pm.setComponentEnabledSetting(
//                new ComponentName(getApplication(), MyNotificationListenerService.class),
//                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
//    }

    private void initData() {
        macAddress = spUtils.getString("macAddress", "");
        if (!TextUtils.isEmpty(macAddress)) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(0);
                }
            }, 200);
        }
    }

    private void initRecyclerView() {
        Log.i(TAG, "initRecyclerView: " + (listAdapter == null ? true : false));
       tv_device_name =(EditText)   findViewById(R.id.tv_device_name);
        ed_ver  =(EditText)  findViewById(R.id.ed_ver);
        etFilePath  =(EditText)  findViewById(R.id.ed_file);
        recyclerView.setHasFixedSize(true);
        listAdapter = new SearchListAdapter();
        recyclerView.setAdapter(listAdapter);
//        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }


    private void initListener() {
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (TextUtils.isEmpty(etFilePath.getText().toString())) {
                    Toast.makeText(MainActivity.this, "升级的固件路径不能为空！", Toast.LENGTH_LONG).show();
                    return;
                }
                bandCommAgent.findAllDevices(10000, new BLEScanner.OnBLEScanListener() {
                    @Override
                    public void onScanResult(BluetoothDevice device, int rssi, byte[] scanRecord) {
                        String val = tv_device_name.getText().toString().toLowerCase();
                        BLELogUtil.i(val);
                        if (device.getName().toLowerCase().indexOf(val) > -1) {
                            if (!deviceAddressList.contains(device.getAddress())) {
                                deviceAddressList.add(device.getAddress());
                                listAdapter.addData(new DeviceInfo(device.getName(), device.getAddress()));
                            }
                        }
                    }

                    @Override
                    public void onScanFailed(BLEException bleException) {
                        BLELogUtil.i("扫描结束 1秒后  自动连接第一个" + ed_ver.getText().toString());
                        App.ver = ed_ver.getText().toString();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                foreachDevce(index);
                            }
                        }, 1000);
                    }
                });
            }
        });

//        listAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                onClickTime = System.currentTimeMillis();
//                if (onClickTime - mLastClickTime < 5000) {
//                    return;
//                }
//                spUtils.clear();
//                mLastClickTime = onClickTime;
//                final BluetoothDevice bean = (BluetoothDevice) adapter.getData().get(position);
//                if (bean != null) {
//                    final String address = bean.getAddress();
//                    Log.i(TAG, "onItemChildClick: " + address);
//                    boolean connect = bandCommAgent.connect(bean);
//                    Log.i(TAG, "onItemChildClick: " + connect);
//                    //boolean connect = penCommAgent.connect(address);
//                    CustomProgressDialog.show(MainActivity.this);
//                }
//            }
//        });


    }
    BluetoothSignalListener  bluetootSign =       new BluetoothSignalListener() {
            @Override
            public void onConnected(final String mac) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spUtils.put("macAddress", mac);
                        App.isFinsh =false;
                        CustomProgressDialog.stop();
                        App.ver = ed_ver.getText().toString();
                        App.filepath = etFilePath.getText().toString();
                        Toast.makeText(MainActivity.this, "连接成功"+   App.ver, Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(MainActivity.this, TestActivity.class);
                        startActivity(intent);


//                        bandCommAgent.getDeviceFirmwareVersion();





                    }
                });
            }

            @Override
            public void onConnectionFailed(final BLEException bleException, int status) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomProgressDialog.stop();
                        Toast.makeText(MainActivity.this, "连接失败" + bleException.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }


            @Override
            public void onDisconnect() {

            }

            @Override
            public void onReceiveMacAddress(String macAddress) {

            }

            @Override
            public void onReceiveDeviceFirmwareVersion(String versionCode) {
                Log.i(TAG, "onReceiveDeviceFirmwareVersion" + versionCode);
                checkUpdate(versionCode);

            }

            @Override
            public void onSetDeviceTimeResponse(boolean isSuccess) {

            }

            @Override
            public void onReadDeviceTime(DeviceTimeBean bean) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年:MM月:dd日:HH时:mm分:ss秒");
                String format = sdf.format(new Date(bean.getDeviceTime()));
                Log.i(TAG, "onReadDeviceTime: " + format);
            }

            @Override
            public void onClearDataResponse(boolean isSuccess) {

            }

            @Override
            public void onSetPersonalInfoResponse(boolean isSuccess) {

            }

            @Override
            public void onGetDeviceBattery(String battery) {

            }

            @Override
            public void onSetSedentaryAlarm(boolean isSuccess) {

            }

            @Override
            public void onTakePhotoSuccess() {

            }

            @Override
            public void onSetDeviceParameterResponse(boolean isSuccess) {

            }

            @Override
            public void onFindDeviceSuccess() {

            }

            @Override
            public void onReadDeviceRealStep(Long step) {

            }

            @Override
            public void onReadDeviceSportAndSleepDataResponse(Long record_step_steps, int deepSleep, int lightSleep) {

            }

            @Override
            public void onAppPushToDeviceResponse(boolean isSuccess) {

            }

            @Override
            public void onControlDeviceResponse(boolean isSuccess) {

            }

            @Override
            public void onReadHeartRateResponse(int heartRate) {

            }

            @Override
            public void onReadBloodpressure(int highPressure, int lowPressure) {

            }

        };




    private static boolean checkSDK() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: ");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        bandCommAgent.disconnect();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private  Handler handler=new Handler();
    void foreachDevce(final int index) {

        BLELogUtil.i("升级进行中！" +index);
        if (this.listAdapter == null ||   index  >=listAdapter.getData().size()  ) {
            BLELogUtil.i("升级完成！");
            Toast.makeText(this, "升级完成！", Toast.LENGTH_LONG).show();
            return;
        }
        //spUtils.clear();
        mLastClickTime = onClickTime;
        //一点5秒后连接下一个
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                DeviceInfo bean = (DeviceInfo) listAdapter.getData().get(index);
                if (bean != null) {
                    final String address = bean.getAddress();
                    Log.i(TAG, "onItemChildClick: " + address);
                    bandCommAgent.setBluetoothSignalListener(bluetootSign);
                    boolean connect = bandCommAgent.connect(bean.getAddress());
                    Log.i(TAG, "onItemChildClick: " + connect);
                    //boolean connect = penCommAgent.connect(address);
                    CustomProgressDialog.show(MainActivity.this);
                }
            }
        },2000);

    }

    @Override
    protected void onResume() {
        super.onResume();
       if( App.isFirst){
           foreachDevce(++index);
       }
    }

    public  void checkUpdate(String data){
//        String da = data.replace("v", "").replace("V", "");
      //  if (!TextUtils.isEmpty(da) && Float.parseFloat(da) < 1.1) {
//            BLELogUtil.i("需要升级...");
//            readFile();
//        } else {
//            BLELogUtil.i("不需要升级... 下一个");
//            index++;
//            foreachDevce(index);
//        }
    }


    int REQUEST_GET_FILE=9865;

        public void getFile(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_GET_FILE);
        }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_GET_FILE) {
                Uri uri = data.getData();
                String path = "";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        path = getRealPathFromURI(uri);
                    } catch (Exception e) {
                        e.printStackTrace();
                        path = uri.getPath();
                    }
                } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
                    path = uri.getPath();
                }
                etFilePath.setText(path);
                App.filepath= path;
            }
        }
    }
    public String getRealPathFromURI(Uri contentUri) throws Exception {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }


}
